package com.think.common.enums.serialize;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.think.common.enums.IEnum;
import org.springframework.beans.BeanUtils;

import java.io.IOException;

/**
 * <p>
 * jackson IEnum 反序列化器
 * </p>
 *
 * @author xwj
 * @date 2019/4/11
 */
public class IEnumDeserializer<E extends IEnum> extends StdDeserializer<E> {

    public IEnumDeserializer(Class<E> enumType) {
        super(enumType);
    }

    @Override
    public E deserialize(JsonParser jp, DeserializationContext context) throws IOException {
        String currentName = jp.currentName();
        Object currentValue = jp.getCurrentValue();
        Class findPropertyType = BeanUtils.findPropertyType(currentName, currentValue.getClass());
        for (Object e : findPropertyType.getEnumConstants()) {
            E rs = (E)e;
            if (rs.getValue().equals(jp.getValueAsInt()) || rs.getValue().toString().equals(jp.getValueAsString())) {
                return rs;
            }
        }
        return null;
    }
}
